﻿using System;
using System.Diagnostics;
using System.IO;


namespace Htm2Pdf.Convertor
{
    public class PdfConvertor
    {
        public static void Convert(string htmUrl, string wkHtmlPath, string outputDirectory)
        {
            if (htmUrl.StartsWith("http://") == false)
                htmUrl = "http://" + htmUrl;


            UrlChecker.CheckUrl(htmUrl);

            Uri uri = new Uri(htmUrl);

            string fileName = uri.DnsSafeHost + uri.AbsolutePath;

            char [] restrictedChars = new []{'/', '\\', '|', ':', '*', '\"', '?', '>', '<', ' '};

            foreach (var restrictedChar in restrictedChars)
            {
                fileName = fileName.Replace(restrictedChar, '-');
            }

            fileName = fileName.Trim();


            string outputPdfPath = Path.Combine(outputDirectory, fileName + ".pdf");

            using (Process p = new Process())
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();

                startInfo.RedirectStandardOutput = true;
                startInfo.UseShellExecute = false;
                startInfo.FileName = wkHtmlPath;

                startInfo.Arguments = htmUrl + " " + outputPdfPath;
                p.StartInfo = startInfo;

                try
                {
                    p.Start();
                    p.WaitForExit();
                }
                catch(Exception ex)
                {
                    throw new PdfConvException(string.Format("Unable to create pdf for url '{0}'", htmUrl), ex);
                }


                if (File.Exists(outputPdfPath) == false)
                {
                    throw new PdfConvException(string.Format("Unable to create pdf for url '{0}'", htmUrl));
                }
            }

            string thumbFilename = Path.Combine(outputDirectory, uri.Host + ".thumbnail.png");

            try
            {
                ThumbGenerator.Generate(outputPdfPath, thumbFilename);
            }
            catch (Exception ex)
            {
                throw new PdfConvException(string.Format("Unable to create thumb for pdf '{0}'", outputPdfPath), ex);
            }
            
        }
    }
}
